extends CharacterBody3D

@onready var character: CharacterBody3D = $"."
@onready var spring_arm_camera: SpringArm3D = $SpringArm3D
@onready var animation_tree: AnimationTree = $"../../AnimationTree"

@export var look_speed: float = 0.5
@export var move_speed: float = 7.0
@export var acceleration: float = 15

var mouse_captured: bool = false

# 鼠标左右上下移动
func _unhandled_input(event: InputEvent) -> void:
	if !mouse_captured and Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT):
		Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED)
		mouse_captured = true
	elif mouse_captured and Input.is_key_pressed(KEY_ESCAPE):
		Input.set_mouse_mode(Input.MOUSE_MODE_VISIBLE)
		mouse_captured = false

	if mouse_captured and event is InputEventMouseMotion:
		rotate_look(event.relative)

# 也可使用rotate_x, rotate_y, rotate_z等方法
func rotate_look(relative: Vector2) -> void:
	# 上下旋转, 限制上下旋转的角度
	spring_arm_camera.rotation_degrees.x -= relative.y * look_speed
	spring_arm_camera.rotation_degrees.x = clamp(spring_arm_camera.rotation_degrees.x, -45, 30)

	# 左右旋转，环绕
	spring_arm_camera.rotation_degrees.y -= relative.x * look_speed
	spring_arm_camera.rotation_degrees.y = wrapf(spring_arm_camera.rotation_degrees.y, 0, 360.0)


@export var movement_animation_transition_speed = 0.15

var current_input: Vector2
var current_velocity: Vector2

func _process(delta: float) -> void:
	var velocityDelta = (current_input - current_velocity)
	if velocityDelta.length() > movement_animation_transition_speed:
		velocityDelta = velocityDelta.normalized() * movement_animation_transition_speed

	current_velocity += velocityDelta
	var animation_velocity = current_velocity
	animation_velocity.y *= -1
	var velocity_value = maxf(absf(animation_velocity.x), absf(animation_velocity.y))
	if velocity_value != 0 and velocity_value != 1:
		print(velocity_value)
	#animation_tree.set("parameters/Movement/UnfocusMovement/blend_position", velocity_value)

func _physics_process(delta: float) -> void:
	move_character(delta)

func move_character(delta: float) -> void:
	current_input = Input.get_vector("move_left", "move_right", "move_up", "move_down") # 获取输入向量
	# 绕指定轴旋转，将输入向量转为角色(即相机)的朝向
	var dir = Vector3(current_input.x, 0, current_input.y).rotated(Vector3.UP, spring_arm_camera.rotation.y)
	character.velocity = lerp(character.velocity, dir * move_speed, delta * acceleration)
	character.move_and_slide()
